const db = uniCloud.database();
const dbJQL = uniCloud.databaseForJQL()
const dbCmd = db.command
module.exports = {
	_before: function() { // 通用预处理器
		// 开始的时间
		this.startTime = Date.now()
		this.params = {
			name: "ABC"
		};
		this.clientInfo = this.getClientInfo();
		//  主动抛出一个错误，中断当前代码的执行，并将错误信息返回给调用方
		if (false) {
			throw new Error("没有权限");
		}
	},
	// 不传值时默认size=3
	async getUser({size = 3} = params) {
		// !isNaN(size) ：
		// 取反操作，表示 "如果 size 是有效数字"
		if (!isNaN(size)) {
			size = Number(size)
		} else {
			return {
				errMsg: "参数格式有误，需要number类型"
			}
		}
		let res = await dbJQL.collection("demo-user")
			.limit(size)
			.get()
		return res;
	},
	async addUser(params = {}) {
		let res = await dbJQL.collection("demo-user")
			.add(params)
		return res;
		console.log(res);
	},
	async updateUser(id = "") {
		let res = await dbJQL.collection("demo-user")
			.doc(id)
			.update({
				like: ["唱", "跳", "rap", "篮球"]
			})
		// let res = await db.collection("demo-user")
		// 	.doc(id)
		// 	.update({
		// 		like: dbCmd.push(["踢足球"]),
		// 	})
		console.log(res);
	},
	async removeUser(id = "") {
		let res = await dbJQL.collection("demo-user")
			.doc(id)
			.remove();
		console.log(res);
	},

	async demo() {
		/* 	let username = "匿名" + Math.random().toString(36).substring(3, 9);
			let rdmage = Math.floot(Math.random() * (50 - 10 + 1) + 10) + "";
			let res = await dbJQL.collection("demo-user")
				.add({
					name: username,
					age: rdmage
				});
			return res */
	},

	_after(error, result) {
		if (error) {
			throw error
		}
		// 追加
		// result.author = "ABC"

		// 查询数据用了多少时间
		// result.timeCost = Date.now() - this.startTime

		return result;
	},

	async _timing() {
		let username = "匿名" + Math.random().toString(36).substring(3, 9);
		let rdmage = Math.floor(Math.random() * (50 - 10 + 1)) + 10 + "";
		let res = await dbJQL.collection("demo-user").add({
			name: username,
			age: rdmage
		})
		console.log(res);
		return res;
	}

}